/**
 *@description:TODO
 * @author: cai
 *@time:2018年2月2日上午10:31:05
 */
package com.pos.modules.cashier;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.basewin.aidl.OnPrinterListener;
import com.basewin.services.ServiceManager;
import com.google.gson.JsonObject;
import com.pos.BaseActivity;
import com.pos.ExampleUtil;
import com.pos.LocalBroadcastManager;
import com.pos.R;
import com.pos.YourApplication;
import com.pos.modules.ScannerActivity;
import com.pos.modules.bean.UserBean;
import com.pos.modules.cashier.bean.AccountGoodsBean;
import com.pos.net.base.Request.Method;
import com.pos.net.netparam.NetParams;
import com.pos.net.netparam.RequestUrls;
import com.pos.net.request.StringNetRequest;
import com.pos.net.request.interfa.BaseRequestListener;
import com.pos.net.request.interfa.JsonRequestListener;
import com.pos.net.request.interfa.StringRequestListener;
import com.pos.toolbox.FinancialUtils;
import com.pos.toolbox.QRCodeUtil;
import com.pos.toolbox.RSAUtils;
import com.pos.toolbox.file.FilesManager;
import com.pos.toolbox.system.DeviceAttribute;
import com.pos.widgets.ActionBarManager;
import com.pos.widgets.ScanGunKeyEventHelper;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import cn.jpush.android.api.JPushInterface;

/**
 * @description:扫码支付(我扫你，你扫我)
 * @author cai
 * @time:2018年2月2日上午10:31:05
 */
public class ScannerPayActivity2 extends BaseActivity implements ScanGunKeyEventHelper.OnScanSuccessListener {
	private TextView text_name, text_amount, text_time,pay_success;
	private ImageView imageView;
	private int payType = 0;
	private String merId, tstTypeId, amount, threeOrdNum, memberPayToken;
	private String ageOrdId, ageOrdIdMicro;
	private int timeNum = 0;
	private Timer mTimer = null;
	private TimerTask mTimerTask = null;
	private final static int OPEN_TIMER = 0;
	private final static int CLOSE_TIMER = 1;
	private UserBean userBean;
	/**
	 * 二维码图片字符串
	 */
	private String payInfo;
	private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private StringNetRequest stringNetRequest;
	/**
	 * 支付方式,0为扫码枪扫码，1为生成二维码方式
	 */
	private int type = 0;

	private TextView text_common_title;
	private LinearLayout linear_title_back;
	private ImageView image_common_title_function;
	private TextView text_tip_one, text_tip_two, text_swich;
	private ScanGunKeyEventHelper mScanGunKeyEventHelper;
	private PrinterListener printer_callback = new PrinterListener();
	JSONObject printJson = new JSONObject();
	private String goodinfo="";
	private long finalPrice,discountPrice;
	private EditText editText;
	public static boolean isForeground = false;
	private boolean  ispay=false;


	private String dayinxinxi="";
	@Override
	protected void onResume() {
		super.onResume();
		isForeground = true;
		Log.e(Tag, "CashierActivity    onResume********");
		if (!mScanGunKeyEventHelper.hasScanGun()) {
			// Toast.makeText(mContext, "未检测到扫码枪设备", Toast.LENGTH_SHORT).show();
			Log.e("TAG", "onResume: "+"111111" );
		}
	}
	@Override
	protected void onPause() {
		isForeground = false;
		super.onPause();
	}
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	public class PrinterListener implements OnPrinterListener {

		@Override
		public void onStart() {
			// TODO 打印开始
			// Print start
			// Log.d(TAG, getStr(R.string.print_start));
			// sb.append(getStr(R.string.print_start) + "\n");
			// showText(sb);
			Log.e(Tag, "PrinterListener onStart");
		}

		@Override
		public void onFinish() {
			// TODO 打印结束
			// End of the print
			// Log.d(TAG, getStr(R.string.print_end));
			// sb.append(getStr(R.string.print_end) + "\n");
			// showText(sb);
			Log.e(Tag, "PrinterListener onFinish");

		}

		@Override
		public void onError(int errorCode, String detail) {
			// TODO 打印出错
			// print error
			// Log.d(TAG, getStr(R.string.print_error) + " errorcode = " +
			// errorCode + " detail = " + detail);
			// sb.append(getStr(R.string.print_error) + errorCode + " detail = "
			// + detail + "\n");
			// showText(sb);
			Log.e(Tag, "PrinterListener onError " + detail);

		}
	};
	/**
	 * 截获按键事件.发给ScanGunKeyEventHelper
	 *
	 * @param event
	 * @return
	 */
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {

		if (mScanGunKeyEventHelper.isScanGunEvent(event)) {
			mScanGunKeyEventHelper.analysisKeyEvent(event);
			return true;
		}
		return super.dispatchKeyEvent(event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		closeTimer();
		unregisterReceiver(stateChangeReceiver);
		mScanGunKeyEventHelper.onDestroy();
		LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
	}

	@Override
	public void initView() {
		setContentView(R.layout.scanner_pay_layout2);
		registerMessageReceiver();
		text_name = bindId(R.id.text_name);
		text_amount = bindId(R.id.text_amount);
		text_time = bindId(R.id.text_time);
		imageView = bindId(R.id.imageView);
		text_common_title = bindId(R.id.text_common_title);
		linear_title_back = bindId(R.id.linear_title_back);
		image_common_title_function = bindId(R.id.image_common_title_function);
		text_tip_one = bindId(R.id.text_tip_one);
		text_tip_two = bindId(R.id.text_tip_two);
		text_swich = bindId(R.id.text_swich);
		editText=bindId(R.id.code);
		editText.setText("");
		editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

				if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
					switch (event.getAction()) {
						case KeyEvent.ACTION_UP:

							if (TextUtils.isEmpty(editText.getText().toString())) {
								showShortToast("请输入商品码");
								return false;
							}
							InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
							imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
						//	Toast.makeText(ScannerPayActivity2.this,"输入框"+editText.getText().toString(),Toast.LENGTH_LONG).show();
							Log.e("onEditorAction", "onEditorAction*******goodsCode=" + editText.getText().toString() + "******");
							startPay(editText.getText().toString());
							return true;

						default:
							return true;
					}

				}
				return false;
			}
		});
	}

	@Override
	public void initData() {
		pay_success=bindId(R.id.pay_success);
		finalPrice=getIntent().getLongExtra("finalprice",0);
		discountPrice=getIntent().getLongExtra("discountprice",0);
		goodinfo=getIntent().getStringExtra("goodInfo");
		mScanGunKeyEventHelper = new ScanGunKeyEventHelper(this);
		registerBoradcastReceiver();
		stringNetRequest = StringNetRequest.getInstance(mContext);
		stringNetRequest.setMainContext(mContext);
		userBean = (UserBean) FilesManager.readObject(mContext, FilesManager.User);
		payType = getIntent().getIntExtra("payType", 0);

		merId = getIntent().getStringExtra("merId");

		tstTypeId = getIntent().getStringExtra("tstTypeId");
		memberPayToken = getIntent().getStringExtra("memberPayToken");
		amount = getIntent().getStringExtra("amount");
		threeOrdNum = getIntent().getStringExtra("threeOrdNum");
		text_name.setText(userBean.getMerName());
		text_amount.setText("订单金额：" + amount + "元");
		pay_success.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(type==1){
					Log.e("TAG", "setCostomMsg: "+ageOrdId );
					paySuccessNotice(ageOrdId);

				}else{
					Log.e("TAG", "setCostomMsg: "+ageOrdIdMicro );
					paySuccessNotice(ageOrdIdMicro);
				}
			}
		});

		String title = "微信支付";
		switch (payType) {
			case 1:
				title = "微信支付";
				break;
			case 2:
				title = "支付宝支付";
				break;
			case 3:
				title = "翼支付";
				if (merId.equals("M_1803260000002225249")||merId.equals("M_1803260000002349518")||merId.equals("M_1803260000002423137")||merId.equals("M_1803060000001868744")) {
					text_swich.setVisibility(View.GONE);
				}else{
					text_swich.setVisibility(View.VISIBLE);
				}

				break;
			case 4:
				title = "银联支付";
				break;
			default:
				break;
		}
		text_common_title.setText(title);
		linear_title_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();

			}
		});
		image_common_title_function.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startScanner();
			}
		});
		
		//收购完成隐藏
	/*	Handler handler=new Handler();
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				pay_success.setVisibility(View.VISIBLE);
			}
		},10000);*/


	}

	@Override
	public void initListener() {

		text_time.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (timeNum == 0) {
					openTimer();
					checkResultRegular();
				}

			}
		});

		text_swich.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				swichType();

			}

		});

	}

	/**
	 * 切换扫码枪方式和生成二维码方式
	 */
	private void swichType() {
		// 当前为扫码枪方式
		if (type == 0) {
			// 切换为生成二维码方式
			type = 1;
			text_time.setVisibility(View.VISIBLE);
			text_time.setText("60s");
			text_tip_one.setVisibility(View.GONE);
			text_tip_two.setVisibility(View.VISIBLE);
			text_swich.setText("切换为扫码枪支付");
			imageView.setVisibility(View.VISIBLE);
			image_common_title_function.setVisibility(View.GONE);
			getScannerImage();
		} else {
			// 切换为扫码枪方式
			type = 0;
			closeTimer();
			text_time.setVisibility(View.INVISIBLE);
			text_time.setText("0");
			text_tip_one.setVisibility(View.VISIBLE);
			text_tip_two.setVisibility(View.GONE);
			text_swich.setText("切换为二维码支付");
			imageView.setVisibility(View.GONE);
			image_common_title_function.setVisibility(View.VISIBLE);

		}

	}

	private void startScanner() {
		closeTimer();
		startActivityForResult(new Intent(mContext, ScannerActivity.class), 0);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == 0) {
				String authCode = data.getStringExtra("goodsCode");
				Log.e("authCode", "authCode=" + authCode);
				startPay(authCode);
			} else if (requestCode == 1) {
				setResult(RESULT_OK);
				finish();
			}

		}
	}

	@Override
	public void onScanSuccess(String barcode) {
		Toast.makeText(this,"00"+barcode,Toast.LENGTH_LONG).show();
		Log.e("TAG", "onScanSuccess: "+barcode );
		Log.e(Tag, "onScanSuccess barcode=" + barcode);
		System.out.println("************barcode=" + barcode);
		if (type == 1) {
			return;
		}
		String authCode = barcode;
		Log.e("authCode", "authCode=" + authCode);
		startPay(authCode);
	}

	private void registerBoradcastReceiver() {
		IntentFilter filter1 = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
		IntentFilter filter2 = new IntentFilter(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
		registerReceiver(stateChangeReceiver, filter1);
		registerReceiver(stateChangeReceiver, filter2);
	}

	private BroadcastReceiver stateChangeReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

			if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
				// Toast.makeText(mContext, "蓝牙设备连接状态已变更",
				// Toast.LENGTH_SHORT).show();
			} else if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
				// Toast.makeText(mContext, "蓝牙设备连接状态已变更",
				// Toast.LENGTH_SHORT).show();
			}
		}
	};

	/**
	 * 开始倒计时
	 */
	private void openTimer() {
		timeNum = 60;
		if (mTimer == null) {
			mTimerTask = new TimerTask() {
				public void run() {
					Message msg = new Message();
					if (timeNum > 0) {
						timeNum--;
						msg.what = OPEN_TIMER;
						msg.arg1 = timeNum;
					} else {
						msg.what = CLOSE_TIMER;
					}
					mHandler.sendMessage(msg);
				}
			};
			mTimer = new Timer();
			mTimer.schedule(mTimerTask, 1000, 1000);
		}
	}

	/**
	 * 关闭timer与task
	 */
	private void closeTimer() {
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		if (mTimerTask != null) {
			mTimerTask.cancel();
			mTimerTask = null;
		}
	}

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case OPEN_TIMER:
					text_time.setText(msg.arg1 + "s");
					break;

				case CLOSE_TIMER:
					closeTimer();
					text_time.setText("已超时,支付失败,点击重试");
					break;
			}

		}
	};

	/**
	 * 获取扫码图片
	 */
	private void getScannerImage() {
		ageOrdId = android.os.Build.SERIAL + "_" + System.currentTimeMillis();
		System.out.println("*****ageOrdId=" + ageOrdId);
		if (ageOrdId.length() > 32) {
			ageOrdId = ageOrdId.substring(ageOrdId.length() - 32, ageOrdId.length());
		}
		System.out.println("*****ageOrdId=" + ageOrdId);
		JSONObject object = new JSONObject();
		try {
			object.put("ageOrdId", threeOrdNum);
			object.put("merId", merId);
			object.put("tstTypeId", tstTypeId);
			object.put("amount", amount);
			object.put("merName", userBean.getStoreName());
			object.put("threeOrdNum", threeOrdNum);
			object.put("RegistrationID",JPushInterface.getRegistrationID(this));
		} catch (JSONException e) {
			e.printStackTrace();
		}

		Log.e(Tag, "object.toString()=" + object.toString());
		Log.e(Tag, "RSAUtils.encode(object.toString())=" + RSAUtils.encode(object.toString()));
		Log.e("TAG", "getScannerImage: "+object.toString() );
		stringNetRequest.startRequest(RequestUrls.scanUrl, Method.POST, RSAUtils.encode(object.toString()), 0,
				listenerString);
	}

	/**
	 * 轮询订单(每3秒一次)
	 */
	private void checkResultRegular() {
		/*new Handler().postDelayed(new Runnable() {
			public void run() {
				checkResult();
			}
		}, 3000);*/
	}

	/**
	 * 查询订单结果
	 */
	private void checkResult() {
		JSONObject object = new JSONObject();

		try {
			object.put("ageOrdId", ageOrdId);
			object.put("merId", merId);

		} catch (JSONException e) {
			e.printStackTrace();
		}

		Log.e(Tag, "object.toString()=" + object.toString());
		Log.e(Tag, "RSAUtils.encode(object.toString())=" + RSAUtils.encode(object.toString()));

		stringNetRequest.startRequest(RequestUrls.queryUrl, Method.POST, RSAUtils.encode(object.toString()), 1,
				listenerString);
	}

	/**
	 * pos扫码用户二维码后，进入支付
	 */
	private void startPay(String authCode) {
		editText.setText("");
		JSONObject object = new JSONObject();
		ageOrdIdMicro = android.os.Build.SERIAL + "_" + System.currentTimeMillis();
		if (ageOrdIdMicro.length() > 32) {
			ageOrdIdMicro = ageOrdIdMicro.substring(ageOrdIdMicro.length() - 32, ageOrdIdMicro.length());
		}
		try {
			object.put("ageOrdId", threeOrdNum);
			object.put("merId", merId);
			object.put("tstTypeId", tstTypeId);
			object.put("amount", amount);
			object.put("threeOrdNum", threeOrdNum);
			object.put("authCode", authCode);
			object.put("merName", userBean.getStoreName());
			object.put("RegistrationID",JPushInterface.getRegistrationID(this));
		} catch (JSONException e) {
			e.printStackTrace();
		}

		Log.e(Tag, "object.toString()=" + object.toString());
		Log.e(Tag, "RSAUtils.encode(object.toString())=" + RSAUtils.encode(object.toString()));
		//	Toast.makeText(this,RSAUtils.encode(object.toString()),Toast.LENGTH_SHORT).show();
		Log.e("TAG", "startPay: "+RSAUtils.encode(object.toString()) );
		stringNetRequest.startRequest(RequestUrls.mircoUrl, Method.POST, RSAUtils.encode(object.toString()), 2,
				listenerString);
	}

	/**
	 * 支付成功通知
	 */
	private void paySuccessNotice(String ageOrdIdSelf) {
		//startPrintAndOut(printInfo,jsonResult.optString("orderCode"));
		/*ContentValues values = new ContentValues();
		values.put("id",threeOrdNum);
		values.put("payStatus","0");
		values.put("payMethod",payType+"");
		values.put("payBillNumber",getIntent().getStringExtra("orderCode"));
		values.put("payDate",format.format(new Date()));
		values.put("payAmount",FinancialUtils.yuanToFen(amount));
		values.put("cashAmount","0");
		values.put("cashChange","0");
		values.put("memberPayToken",memberPayToken);
		values.put("secondPayNumber",ageOrdIdSelf);
		values.put("merCode","");
		values.put("merName","");
		values.put("termCode","");
		values.put("bankName","");
		values.put("bankCard","");
		values.put("bankCardExpired","");
		values.put("authorCode","");
		values.put("tradeBatchCode","");
		values.put("orderCode",getIntent().getStringExtra("orderCode"));

		boolean flag = YourApplication.orderDatabaseHelper.insertData(values);
		Log.e("TAG", "paySuccessNotice: "+flag );

		netRequest.startRequest(RequestUrls.hostUrl + RequestUrls.posPayOrderSuccess, Method.POST,
				NetParams.posPayOrderSuccess(mContext, threeOrdNum, 0, payType, ageOrdIdSelf, format.format(new Date()),
						FinancialUtils.yuanToFen(amount), 0, 0, memberPayToken, ageOrdIdSelf, "", "", "", "", "", "",
						"", "",getIntent().getStringExtra("orderCode")),
				3, listener1);*/
		startPrint(payType,format.format(new Date()),getIntent().getStringExtra("orderCode"),android.os.Build.SERIAL,"","","","","","");
		Intent intent = new Intent(mContext, PaySuccessActivity.class);
		intent.putExtra("printInfo", dayinxinxi);
		intent.putExtra("totalPrice",  FinancialUtils.yuanToFen(amount));
		intent.putExtra("orderCode", getIntent().getStringExtra("orderCode"));
		Log.e("TAG", "paySuccessNotice: "+amount );
		startActivityForResult(intent, 1);

		Log.e("TAG", "paySuccessNotice:orderId "+threeOrdNum+"ordercode:"+getIntent().getStringExtra("orderCode") );
	}

	private BaseRequestListener listener1 = new JsonRequestListener() {

		@Override
		public void onStart(int requestId) {
			showDialg();
		}

		@Override
		public void onError(int requestId, int errorCode, String errorMsg) {
			disMissDialog();
			dealError(errorCode, errorMsg);

		}

		@Override
		public void onSuccess(int requestId, String url, JSONObject jsonResult) {
			disMissDialog();
			Log.e("TAG", "11111111111onSuccess: "+jsonResult.toString() );
			String memberCode = jsonResult.optString("memberCode");
			String memberName = jsonResult.optString("memberName");
			String memberLevel = jsonResult.optString("memberLevel");
			String memberScore = jsonResult.optString("memberScore");
			String menberBalance = jsonResult.optString("menberBalance");
			String printInfo = jsonResult.optString("printInfo");

			Intent intent = new Intent(mContext, PaySuccessActivity.class);
			intent.putExtra("memberCode", memberCode);
			intent.putExtra("memberName", memberName);
			intent.putExtra("memberLevel", memberLevel);
			intent.putExtra("memberScore", memberScore);
			intent.putExtra("printInfo", printInfo);
			intent.putExtra("totalPrice", FinancialUtils.yuanToFen(amount));
			intent.putExtra("payBillNumber",jsonResult.optString("orderCode"));
			startActivityForResult(intent, 1);
			//	startPrintAndOut(printInfo,jsonResult.optString("orderCode"));
		}
	};

	private BaseRequestListener listenerString = new StringRequestListener() {

		@Override
		public void onStart(int requestId) {
			if (requestId != 1)
				showDialg();
		}

		@Override
		public void onError(int requestId, int errorCode, String errorMsg) {
			disMissDialog();
			// dealError(errorCode, errorMsg);
		}

		@Override
		public void onSuccess(int requestId, String url, String jsonResult1) {
			disMissDialog();
			Log.e("TAG", "onSuccess2222: "+jsonResult1 );
			//	Log.e("TAG", "onSuccess: "+RSAUtils.decode("eMbzDI8H5CkYKEdK6XAabEO3eJPfpzTthQTwfWpVWdNhwrb3YVjNUmi8uOS9whMIAjFGBMCHMFwgyLsag/dG8bV9Jj/zWlsZM7MhsftnyUvbV6OalbZ1AeUoxS75nDHbXmoVEY+V3YSvwjvPBnRdZdIFFll2QjOKg0fR1a+Nk9iJ1wwaZu4wmrNYGC1J5wJ1jiBfj+r/5/UPOxRpx88V9B72j2ocvnmGFuo5ra7/J8MvGI1rAU5Phsey7Xm+Ia7aKrS9LhjK22joljDhfAbPPv7qLLC+53O839f9mDag1xlM+14YejAwRty9LSGY4gB+M8DLAj0Jbo6ekxYDG0EPcyXDKgdSSZJEq0qv/ys2Vr+4buYJBjQ4NqlU+lb1cRNcvafOVxYf6iK8BAHpptf4fV04+eXWjfyD30eegN3MLW/EI+82peHqwjCW09eTjsyM7/9GQCUUBvUSp0Knih3his3QAozfSLRkNrWzYVF+hksf7bAy39nmc5vWfvf2VpS1DUkGqrnIfEtm/KuNbc3J478bZ5a9gY3KrnnUrCcpXKDdYSpWeJYdFVxTRLva9SPuZ2Okd2QNE1HIORifjn4Qn+i8kamulQT5DHcaT/LZhWNpBr5txGnnqMiAYQrGv/5BCf00fSTq4ncm0wmDKbwIZ3/QP78lmWzEWNv9UKHf0uZBFe6bDa+jl9s9vgdrqJUws5bcwZxsL231SC9t7DxROJwEFKWHDVOGaUeN67+/xN0xgSNm4WAIjZUV04KglqRoaVSW9L86admwjU4OwnKaDcZjrQk33FAOTaEDo3hquHNLUKw8yKJ1zUSxXTn3sFZeoblT/seUFvsDRL+/rJrcGmfob6KVb0zEWdVdKcuaGNyczzSjXndsJknPjjYjakWO0yZMx9NhgYFOYFUuboXzh0/PYd++LYLmt919v2XgeQc/FEB39cpAkwJ/ZU32C9cDxzQRc6q6gjMkRUvGPhXHWw/r348z4NOFIb3sEo7EipYLACpmWs3tFbIY1EBPgs/w") );
			if (TextUtils.isEmpty(jsonResult1)) {
				showShortToast("系统繁忙，暂无数据");
				return;
			}

			String result = null;
			try {
				result = RSAUtils.decode(jsonResult1);
			} catch (Exception e1) {
				showShortToast("支付 功能未开通");
				e1.printStackTrace();
			}
			if (TextUtils.isEmpty(result)) {
				if (requestId == 0) {
					showShortToast("生成二维码失败，支付功能未开通");
					return;
				}
				showShortToast("支付功能未开通");
				return;
			}
			JSONObject jsonResult = null;
			try {
				Log.e(Tag, "从平台解密后得到的结果result=" + result);
				jsonResult = new JSONObject(result);
			} catch (JSONException e) {
				showShortToast("支付功能未开通");
				e.printStackTrace();
			}
			if (jsonResult == null) {
				showShortToast("系统繁忙，请稍后重试");
				return;
			}
			if (jsonResult.optString("state").equalsIgnoreCase("ERROR")) {
				showShortToast(jsonResult.optString("msg"));
				return;
			}

			if (requestId == 0) {
				String payInfo = jsonResult.optString("payInfo");
				if (!TextUtils.isEmpty(payInfo)) {
					Bitmap bitmap = QRCodeUtil.createQRCodeBitmap(payInfo, DeviceAttribute.dip2px(mContext, 200));
					imageView.setImageBitmap(bitmap);
					openTimer();
					checkResultRegular();
				} else {
					showShortToast("生成二维码失败，请稍后再试");
				}
			} else if (requestId == 1) {
				/*if (type == 0) {
					return;
				}*/
				// pos生成二维码后等待支付
				String state = jsonResult.optString("state");
			/*	if (state.equalsIgnoreCase("SUCCESS")) {
					paySuccessNotice(ageOrdId);
				} else {
					if (timeNum == 0) {
						showShortToast("支付失败");
					} else {
						// 继续轮询
						checkResultRegular();
					}
				}*/

			} else if (requestId == 2) {
				// pos机扫码用户后支付
				Log.e("TAG", "onSuccess: "+jsonResult.toString() );
				String state = jsonResult.optString("state");
				/*if (state.equalsIgnoreCase("SUCCESS")) {
					paySuccessNotice(ageOrdIdMicro);
				} else if(state.equalsIgnoreCase("UNPAY")){
					*//*if (timeNum == 0) {
						showShortToast("支付失败");
					} else {*//*
						// 继续轮询
						checkResultRegular();
				//	}
				}else {
					showShortToast("支付失败");
				}*/
			}

		}
	};
	private void startPrintAndOut(String printInfo,String payBillNumber) {
		Log.e("TAG", "startPrintAndOut: "+payBillNumber );
		{
			//	ServiceManager.getInstence().verifyData("2222222");
			try {
				try {
					JSONArray printTest = new JSONArray();

					JSONObject json0 = new JSONObject();
					json0.put("content-type", "txt");
					json0.put("content",printInfo );
					//	json0.put("content", "212123123");
					json0.put("size", "2");
					json0.put("position", "left");
					json0.put("offset", "0");
					json0.put("bold", "0");
					json0.put("italic", "0");
					json0.put("height", "-1");
					JSONObject json1 = new JSONObject();
					json1.put("content-type", "one-dimension");
					json1.put("content",payBillNumber);
					json1.put("size", "3");
					json1.put("position", "left");
					json1.put("offset", "0");
					json1.put("bold", "0");
					json1.put("italic", "0");
					json1.put("height", "-1");
					printTest.put(json0);
					printTest.put(json1);
					printJson.put("spos", printTest);
					// 设置底部空3行
					// Set at the bottom of the empty 3 rows
					com.pos.sdk.printer.PosPrinter.Parameters parameters = ServiceManager.getInstence().getPrinter()
							.getParameters();
					parameters.setPrintGray(5000);
					parameters.setPrintStep(4000);
					parameters.setPrintHeatPoint(1000);
					ServiceManager.getInstence().getPrinter().setParameters(parameters);
					ServiceManager.getInstence().getPrinter().setPrintGray(2000);
					ServiceManager.getInstence().getPrinter().printBottomFeedLine(5);
					ServiceManager.getInstence().getPrinter().print(printJson.toString(), null, printer_callback);
				/*JSONObject jsonObject=new JSONObject();
				JSONArray printTest1 = new JSONArray();

				JSONObject json01 = new JSONObject();
				json0.put("content-type", "one-dimension");
				json0.put("content", "11123123");
				json0.put("size", "2");
				json0.put("position", "left");
				json0.put("offset", "0");
				json0.put("bold", "0");
				json0.put("italic", "0");
				json0.put("height", "-1");
				jsonObject.put("spos", printTest1);
				ServiceManager.getInstence().getPrinter().print(jsonObject.toString(), null, printer_callback);*/
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}


	private void startPrint(final int type, final String dealTime, final String payBillNumber, final String termCode, final String terminalId, final String merchantId, final String cardNo, final String voucherNo, final String authorizationNo, final String referenceNo) {
		{

			Log.e("TAG", "startPrint: "+getIntent().getStringExtra("orderCode") );
			//	ServiceManager.getInstence().verifyData("2222222");
			try {
				try {
					JSONArray printTest = new JSONArray();

					JSONObject json0 = new JSONObject();
					json0.put("content-type", "txt");
					if (type == 4) {
						if (goodinfo.equals("")) {
							json0.put("content", "　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端编号：" + terminalId + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice) + "\n实收：" + FinancialUtils.fenToYuan(finalPrice) + "\n折让: " + discountPrice + "\n支付方式：刷卡支付\n终端号：" + terminalId + "\n商户号：" + merchantId + "\n卡号：" + cardNo + "\n卡类型：贷记卡批次号：000001\n凭证号：" + voucherNo + "\n授权号：" + authorizationNo + "\n参考号：" + referenceNo + "\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端编号：" + terminalId + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：刷卡支付\n终端号：" + terminalId + "\n商户号：" + merchantId + "\n卡号：" + cardNo + "\n卡类型：贷记卡批次号：000001\n凭证号：" + voucherNo + "\n授权号：" + authorizationNo + "\n参考号：" + referenceNo + "\n--------------------------------\n持卡人签名：\n");
							dayinxinxi="　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端编号：" + terminalId + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice) + "\n实收：" + FinancialUtils.fenToYuan(finalPrice) + "\n折让: " + discountPrice + "\n支付方式：刷卡支付\n终端号：" + terminalId + "\n商户号：" + merchantId + "\n卡号：" + cardNo + "\n卡类型：贷记卡批次号：000001\n凭证号：" + voucherNo + "\n授权号：" + authorizationNo + "\n参考号：" + referenceNo + "\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端编号：" + terminalId + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：刷卡支付\n终端号：" + terminalId + "\n商户号：" + merchantId + "\n卡号：" + cardNo + "\n卡类型：贷记卡批次号：000001\n凭证号：" + voucherNo + "\n授权号：" + authorizationNo + "\n参考号：" + referenceNo + "\n--------------------------------\n持卡人签名：\n";

						} else {
							json0.put("content", "　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端编号：" + terminalId + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice) + "\n实收：" + FinancialUtils.fenToYuan(finalPrice) + "\n折让: " + discountPrice + "\n支付方式：刷卡支付\n终端号：" + terminalId + "\n商户号：" + merchantId + "\n卡号：" + cardNo + "\n卡类型：贷记卡批次号：000001\n凭证号：" + voucherNo + "\n授权号：" + authorizationNo + "\n参考号：" + referenceNo + goodinfo + "\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端编号：" + terminalId + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：刷卡支付\n终端号：" + terminalId + "\n商户号：" + merchantId + "\n卡号：" + cardNo + "\n卡类型：贷记卡批次号：000001\n凭证号：" + voucherNo + "\n授权号：" + authorizationNo + "\n参考号：" + referenceNo + goodinfo + "\n--------------------------------\n持卡人签名：\n");
							dayinxinxi="　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端编号：" + terminalId + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice) + "\n实收：" + FinancialUtils.fenToYuan(finalPrice) + "\n折让: " + discountPrice + "\n支付方式：刷卡支付\n终端号：" + terminalId + "\n商户号：" + merchantId + "\n卡号：" + cardNo + "\n卡类型：贷记卡批次号：000001\n凭证号：" + voucherNo + "\n授权号：" + authorizationNo + "\n参考号：" + referenceNo + goodinfo + "\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端编号：" + terminalId + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：刷卡支付\n终端号：" + terminalId + "\n商户号：" + merchantId + "\n卡号：" + cardNo + "\n卡类型：贷记卡批次号：000001\n凭证号：" + voucherNo + "\n授权号：" + authorizationNo + "\n参考号：" + referenceNo + goodinfo + "\n--------------------------------\n持卡人签名：\n";

						}

					} else if (type == 1) {
						if (goodinfo.equals("")) {
							json0.put("content", "　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice) + "\n实收：" + FinancialUtils.fenToYuan(finalPrice) + "\n折让: " + discountPrice + "\n支付方式：微信支付\n综合支付流水号：\n" + payBillNumber + "\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：微信支付\n综合支付流水号：\n" + payBillNumber + "\n--------------------------------\n持卡人签名：\n");
							dayinxinxi="　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice) + "\n实收：" + FinancialUtils.fenToYuan(finalPrice) + "\n折让: " + discountPrice + "\n支付方式：微信支付\n综合支付流水号：\n" + payBillNumber + "\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：微信支付\n综合支付流水号：\n" + payBillNumber + "\n--------------------------------\n持卡人签名：\n";

						} else {
							json0.put("content", "　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice) + "\n实收：" +  FinancialUtils.fenToYuan(finalPrice) + "\n折让: " + discountPrice + "\n支付方式：微信支付\n综合支付流水号：\n" + payBillNumber + goodinfo + "\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：微信支付\n综合支付流水号：\n" + payBillNumber + goodinfo + "\n--------------------------------\n持卡人签名：\n");
							dayinxinxi="　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice) + "\n实收：" +  FinancialUtils.fenToYuan(finalPrice) + "\n折让: " + discountPrice + "\n支付方式：微信支付\n综合支付流水号：\n" + payBillNumber + goodinfo + "\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：微信支付\n综合支付流水号：\n" + payBillNumber + goodinfo + "\n--------------------------------\n持卡人签名：\n";


						}


					} else if (type == 2) {
						if (goodinfo.equals("")) {
							json0.put("content", "　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice) + "\n实收：" + FinancialUtils.fenToYuan(finalPrice) + "\n折让: " + discountPrice + "\n支付方式：支付宝支付\n综合支付流水号：\n" + payBillNumber + "\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：支付宝支付\n综合支付流水号：\n" + payBillNumber + "\n--------------------------------\n持卡人签名：\n");
							dayinxinxi= "　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice) + "\n实收：" + FinancialUtils.fenToYuan(finalPrice) + "\n折让: " + discountPrice + "\n支付方式：支付宝支付\n综合支付流水号：\n" + payBillNumber + "\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：支付宝支付\n综合支付流水号：\n" + payBillNumber + "\n--------------------------------\n持卡人签名：\n";

						} else {
							json0.put("content", "　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice) + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：支付宝支付\n综合支付流水号：\n" + payBillNumber + goodinfo + "\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：支付宝支付\n综合支付流水号：\n" + payBillNumber + goodinfo + "\n--------------------------------\n持卡人签名：\n");
							dayinxinxi="　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice) + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：支付宝支付\n综合支付流水号：\n" + payBillNumber + goodinfo + "\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：支付宝支付\n综合支付流水号：\n" + payBillNumber + goodinfo + "\n--------------------------------\n持卡人签名：\n";

						}

					} else if (type == 3) {
						if (goodinfo.equals("")) {
							json0.put("content", "　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice) + "\n实收：" + FinancialUtils.fenToYuan(finalPrice) + "\n折让: " + discountPrice + "\n支付方式：翼支付\n综合支付流水号：\n" + payBillNumber + "\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：翼支付\n综合支付流水号：\n" + payBillNumber + "\n--------------------------------\n持卡人签名：\n");
							dayinxinxi= "　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice) + "\n实收：" + FinancialUtils.fenToYuan(finalPrice) + "\n折让: " + discountPrice + "\n支付方式：翼支付\n综合支付流水号：\n" + payBillNumber + "\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：翼支付\n综合支付流水号：\n" + payBillNumber + "\n--------------------------------\n持卡人签名：\n";

						} else {
							json0.put("content", "　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice) + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：翼支付\n综合支付流水号：\n" + payBillNumber + goodinfo + "\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：翼支付\n综合支付流水号：\n" + payBillNumber + goodinfo + "\n--------------------------------\n持卡人签名：\n");
							dayinxinxi="　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice) + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：翼支付\n综合支付流水号：\n" + payBillNumber + goodinfo + "\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n终端sn号：" + termCode + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：翼支付\n综合支付流水号：\n" + payBillNumber + goodinfo + "\n--------------------------------\n持卡人签名：\n";

						}

					} else if (type == 0) {
						if (goodinfo.equals("")) {
							json0.put("content", " 　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" +  FinancialUtils.fenToYuan(finalPrice) + "\n实收：" +  FinancialUtils.fenToYuan(finalPrice) + "\n折让: " + discountPrice + "\n支付方式：现金支付\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：现金支付\n--------------------------------\n持卡人签名：\n");
							dayinxinxi=" 　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" +  FinancialUtils.fenToYuan(finalPrice) + "\n实收：" +  FinancialUtils.fenToYuan(finalPrice) + "\n折让: " + discountPrice + "\n支付方式：现金支付\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + "\n支付方式：现金支付\n--------------------------------\n持卡人签名：\n";

						} else {
							json0.put("content", " 　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" +  FinancialUtils.fenToYuan(finalPrice) + "\n实收：" + FinancialUtils.fenToYuan(finalPrice) + "\n折让: " + discountPrice + goodinfo + "\n支付方式：现金支付\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + goodinfo + "\n支付方式：现金支付\n--------------------------------\n持卡人签名：\n");
							dayinxinxi=" 　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" +  FinancialUtils.fenToYuan(finalPrice) + "\n实收：" + FinancialUtils.fenToYuan(finalPrice) + "\n折让: " + discountPrice + goodinfo + "\n支付方式：现金支付\n--------------------------------\n\n========商户存根=========\n　　　　POS 签购单\n　　　　　（消费单）\n商户名称：" + userBean.getStoreName() + "\n交易号: " + getIntent().getStringExtra("orderCode") + "\n交易时间:" + dealTime + "\n应收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n实收：" + FinancialUtils.fenToYuan(finalPrice)  + "\n折让: " + discountPrice + goodinfo + "\n支付方式：现金支付\n--------------------------------\n持卡人签名：\n";

						}
					}

					//	json0.put("content", "212123123");
					json0.put("size", "2");
					json0.put("position", "left");
					json0.put("offset", "0");
					json0.put("bold", "0");
					json0.put("italic", "0");
					json0.put("height", "-1");
					JSONObject json1 = new JSONObject();
					json1.put("content-type", "one-dimension");
					json1.put("content", getIntent().getStringExtra("orderCode"));
					json1.put("size", "3");
					json1.put("position", "left");
					json1.put("offset", "0");
					json1.put("bold", "0");
					json1.put("italic", "0");
					json1.put("height", "-1");
					printTest.put(json0);
					printTest.put(json1);
					printJson.put("spos", printTest);
					// 设置底部空3行
					// Set at the bottom of the empty 3 rows
					com.pos.sdk.printer.PosPrinter.Parameters parameters = ServiceManager.getInstence().getPrinter()
							.getParameters();
					parameters.setPrintGray(5000);
					parameters.setPrintStep(4000);
					parameters.setPrintHeatPoint(1000);
					ServiceManager.getInstence().getPrinter().setParameters(parameters);
					ServiceManager.getInstence().getPrinter().setPrintGray(2000);
					ServiceManager.getInstence().getPrinter().printBottomFeedLine(5);
					ServiceManager.getInstence().getPrinter().print(printJson.toString(), null, printer_callback);
				/*JSONObject jsonObject=new JSONObject();
				JSONArray printTest1 = new JSONArray();

				JSONObject json01 = new JSONObject();
				json0.put("content-type", "one-dimension");
				json0.put("content", "11123123");
				json0.put("size", "2");
				json0.put("position", "left");
				json0.put("offset", "0");
				json0.put("bold", "0");
				json0.put("italic", "0");
				json0.put("height", "-1");
				jsonObject.put("spos", printTest1);
				ServiceManager.getInstence().getPrinter().print(jsonObject.toString(), null, printer_callback);*/
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	//for receive customer msg from jpush server
	private MessageReceiver mMessageReceiver;
	public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
	public static final String KEY_TITLE = "title";
	public static final String KEY_MESSAGE = "message";
	public static final String KEY_EXTRAS = "extras";

	public void registerMessageReceiver() {
		mMessageReceiver = new MessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		filter.addAction(MESSAGE_RECEIVED_ACTION);
		LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
	}

	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
					String messge = intent.getStringExtra(KEY_MESSAGE);
					String extras = intent.getStringExtra(KEY_EXTRAS);
					StringBuilder showMsg = new StringBuilder();
					showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
					if (!ExampleUtil.isEmpty(extras)) {
						showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
					}
					setCostomMsg(messge);
				}
			} catch (Exception e){
			}
		}
	}

	private void setCostomMsg(String msg){
		Log.e("TAG", "setCostomMsg: "+msg );
		try {
			JSONObject  js=new JSONObject(msg);


			if(js.getString("state").equals("SUCCESS")){
				if(type==1){
					Log.e("TAG", "setCostomMsg: "+ageOrdId );
					if(js.getString("ageOrdId").equals(threeOrdNum)&&ispay==false){
						paySuccessNotice(ageOrdId);
						ispay=true;
					}


				}else{
					Log.e("TAG", "setCostomMsg: "+ageOrdIdMicro );
					if(js.getString("ageOrdId").equals(threeOrdNum)&&ispay==false){
						paySuccessNotice(ageOrdIdMicro);
						ispay=true;
					}

				}
			}
			/*msgText.setText(msg);
			msgText.setVisibility(android.view.View.VISIBLE);*/


			JPushInterface.getRegistrationID(this);
			Log.e("TAG", "setCostomMsg: "+JPushInterface.getRegistrationID(this));
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}
